package com.manor.common.utils;

import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

import com.manor.common.CommonAppConfig;
import com.manor.common.CommonAppContext;
import com.manor.common.event.LocationEvent;
import com.manor.common.http.CommonHttpConsts;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;

public class LocationUtil {
    private static final String TAG = "定位";
    private static LocationUtil sInstance;
    private final TencentLocationManager mLocationManager;
    private boolean mLocationStarted;
    private boolean mNeedPostLocationEvent;//是否需要发送定位成功事件

    private LocationUtil() {
        mLocationManager = TencentLocationManager.getInstance(CommonAppContext.sInstance);
    }

    public static LocationUtil getInstance() {
        if (sInstance == null) {
            synchronized (LocationUtil.class) {
                if (sInstance == null) {
                    sInstance = new LocationUtil();
                }
            }
        }
        return sInstance;
    }


    private final TencentLocationListener mLocationListener = new TencentLocationListener() {
        @Override
        public void onLocationChanged(TencentLocation location, int code, String reason) {
            KLog.e(TAG, "---code---" + code + "--reason---" + reason);
            if (code == TencentLocation.ERROR_OK) {
                lng = location.getLongitude();//经度
                lat = location.getLatitude();//纬度

                KLog.e(TAG, location);
                KLog.e(TAG, location.getCityCode());
                KLog.e(TAG, "获取经纬度成功------>经度：" + lng + "，纬度：" + lat + "npccode" + location.getAreaStat());
                if (null != listener) {
                    if (null != location.getCityCode() && !location.getCityCode().equals("")) {
                        CommonAppConfig.getInstance().setLocationInfo(
                                lng, lat,
                                location.getProvince(),
                                location.getCity(),
                                location.getDistrict());
                        upLocation();
                        stopLocation();
                        try {
                            listener.Success(Integer.parseInt(location.getCityCode()));
                        } catch (Exception e) {
                            e.printStackTrace();
                            listener.Success(330108);
                        }
                        listener.Success(330108);
                    }
                }
            }
        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    };
    double lng;
    double lat;

    boolean istype = true;

    public void upLocation() {
        CommonHttpUtil.setLocaiton(lng, lat, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0) {
                    if (mNeedPostLocationEvent) {

                        if (istype && lng > 1) {
                            CommonAppConfig.getInstance().setLocationInfo(lng, lat);
                            EventBus.getDefault().post(new LocationEvent(new BigDecimal(lng + ""), new BigDecimal(lat + "")));
                            istype = false;
                        }
                        if (istype && !SpUtil.getInstance().getStringValue(SpUtil.LOCATION_LNG).equals("")) {
                            CommonAppConfig.getInstance().setLocationInfo(new BigDecimal(SpUtil.getInstance().getStringValue(SpUtil.LOCATION_LNG)).doubleValue(), new BigDecimal(SpUtil.getInstance().getStringValue(SpUtil.LOCATION_LAT)).doubleValue());
                            EventBus.getDefault().post(new LocationEvent(new BigDecimal(SpUtil.getInstance().getStringValue(SpUtil.LOCATION_LNG)), new BigDecimal(SpUtil.getInstance().getStringValue(SpUtil.LOCATION_LAT))));
                            istype = false;
                        }

                        //

                        //        需求变更，暂时去掉
                        //                        CommonHttpUtil.getBaseInfoX(new CommonCallback<UserNBean>() {
                        //                            @Override
                        //                            public void callback(UserNBean bean) {
                        //                                if (bean!=null && bean.getBasics()!=null){
                        //                                    CommonAppConfig.getInstance().setLocationInfo(
                        //                                            lng,
                        //                                            lat,
                        //                                            bean.getBasics().getProvince(),
                        //                                            bean.getBasics().getCity(),
                        //                                            bean.getBasics().getDistrict());
                        //                                }
                        //                            }
                        //                        });


                    }
                }
            }

        });


    }

    private IGetLocationListener listener;

    public interface IGetLocationListener {//创建抽象类

        void Success(int cttyId);//添加抽象方法，可任意添加多个可带参数如void test(String cibtext);往下加就行
    }

    //    public static final int REQUEST_LEVEL_GEO = 0;
    //    public static final int REQUEST_LEVEL_NAME = 1;
    //    public static final int REQUEST_LEVEL_ADMIN_AREA = 3;
    //    public static final int REQUEST_LEVEL_POI = 4;
    //启动定位
    public void startLocation(IGetLocationListener listener) {
        if (this.listener != null) {
            return;
        }
        this.listener = listener;
        if (mLocationManager != null) {

            KLog.e(TAG, "开启定位");
            TencentLocationRequest request = TencentLocationRequest
                    .create()
                    .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA)
                    .setInterval(1000);
            request.setAllowGPS(true);
            request.setIndoorLocationMode(true);

            //当定位周期大于0时, 不论是否有得到新的定位结果, 位置监听器都会按定位周期定时被回调;
            // 当定位周期等于0时, 仅当有新的定位结果时, 位置监听器才会被回调(即, 回调时机存在不确定性).
            // 如果需要周期性回调, 建议将 定位周期 设置为 5000-10000ms
            int code = mLocationManager.requestLocationUpdates(request, mLocationListener);
            KLog.e(TAG, "--code-" + code);
        } else {
            KLog.e(TAG, "mLocationManager == null");
        }
    }

    //停止定位
    public void stopLocation() {
        CommonHttpUtil.cancel(CommonHttpConsts.GET_LOCAITON);
        if (mLocationManager != null) {
            L.e(TAG, "关闭定位");
            mLocationManager.removeUpdates(mLocationListener);

        }
    }

    public void setNeedPostLocationEvent(boolean needPostLocationEvent) {
        mNeedPostLocationEvent = needPostLocationEvent;
    }


}
